package com.zhouchao.messenger1.services;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * 描述：
 * zhougan
 * 2019/2/15
 **/
public class ComputeService extends Service {
    private static final String TAG = ">>>>ComputeService";

    //处理接受到的消息handler
   private Handler acceptHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            Log.i(TAG, "handleMessage: ComputeService接受到消息了");
            Log.i(TAG, "handleMessage: 打印消息message.what="+message.what);
            Log.i(TAG, "handleMessage: 打印消息message.arg1"+message.arg1);
            int result = compute(message.arg1);
            //发送结果给客户端
            Messenger send = message.replyTo;//客户端的Message必须设置此值,服务端才能拿到
            if(send==null){
                return true;
            }
            Message msg = Message.obtain();
            msg.arg1=result;
            msg.what=1001;
            try {
                send.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
                Log.i(TAG, "handleMessage: 发送失败");
            }

            return true;
        }
    });

    private Messenger accept=new Messenger(acceptHandler);

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return accept.getBinder();
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate: ");
        super.onCreate();
    }

    public int compute(int a){
        Log.i(TAG, "handleMessage: 开始计算值 1+2+...+a的和");
        int result=0;
        for(int i=0;i<=a;i++){
            result+=i;
        }
        return result;

    }
}
